﻿using Modbus.Device;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;

namespace UniRlv.Utility.AppLib
{
    public class ModbusDevice:AbtDODevice
    {
        SerialPort serial = new SerialPort();
        int port;
        int bd;
        IModbusSerialMaster master;
        byte slaveId = 1;//从机地址

        public override bool Open()
        {
            if (IsOpen())
            {
                return true;
            }
            else
            {
                serial.PortName = string.Format("COM{0}", port);
                serial.BaudRate = bd;
                serial.RtsEnable = true;

                try
                {
                    serial.Open();
                    master = ModbusSerialMaster.CreateRtu(serial);//连接方式是如RTU

                    return true;
                }
                catch (System.Exception ex)
                {
                    ErrorString = ex.Message;
                    return false;
                }
            }
        }

        public override bool IsOpen()
        {
            return serial.IsOpen;
        }

        public override void Close()
        {
            if (serial.IsOpen)
            {
                serial.Close();
            }
        }

        public override void Pause()
        {
            
        }

        public override void Resume()
        {
            
        }

        public override void SendData(byte[] bytes, int len)
        {
            serial.Write(bytes, 0, len);
        }

        public override string InitString
        {
            get
            {
                return _initString;
            }
            set
            {
                string[] paramStrings = value.Split(',');

                if (paramStrings.Length > 2)
                {
                    slaveId = Convert.ToByte(paramStrings[2]);
                    port = Convert.ToInt32(paramStrings[0]);
                    bd = Convert.ToInt32(paramStrings[1]);

                    _initString = value;
                }
            }
        }

        public override void OutPut(int pin)
        {
            ushort coilAddr = Convert.ToUInt16(pin/8);
            master.WriteSingleCoil(slaveId, coilAddr, true);
        }
    }
}
